package cn.fnst.facecomp.service;

import java.io.Reader;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import cn.fnst.facecomp.model.ComparePhotoNumber;
import cn.fnst.facecomp.utils.Utils;

	public class TotalNumberService {
	protected Logger logger = Logger.getLogger(getClass());
	
	protected static SqlMapClient sqlMapClient;
	
	private static TotalNumberService instance;
	
	private ComparePhotoNumber cpn;
	
	public TotalNumberService() throws Exception{
		Reader reader = Resources.getResourceAsReader ("SqlMapConfig.xml");
		sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
	}
	
	public static synchronized TotalNumberService getInstance() throws Exception{
		if(instance == null){
			instance = new TotalNumberService();
		}
		return instance;
	} 
	
	public synchronized void addRequestNumber(){
		try{
			String day = Utils.getDateString(new Date());
			if(cpn == null || cpn.isOtherDay(day)){
				cpn = getCurrentDayCpn(day);
			}
			cpn.incrementNumber();
			updateCurrentDayCpn(cpn);
		}catch(Exception e){
			logger.error("记录访问次数出错", e);
		}
	}
	
	private void updateCurrentDayCpn(ComparePhotoNumber cpn) throws SQLException{
		sqlMapClient.update("face.updateCurrentDayCpn", cpn);
	}
	
	private ComparePhotoNumber getCurrentDayCpn(String day) throws Exception{
		List<ComparePhotoNumber> list = sqlMapClient.queryForList("face.getCurrentDayCpn", day);
		if(list != null && list.size() > 0){
			return list.get(0);
		}else{
			long totalNumber = getLatestTotalNumber();
			ComparePhotoNumber cpn = new ComparePhotoNumber();
			cpn.setTotalNumber(totalNumber);
			cpn.setDay(day);
			cpn.setCurrentDayNumber(0);
			long id = Long.parseLong(sqlMapClient.queryForObject("face.getComparePhotoNumberID").toString());
			logger.info("new number id: " + id);
			cpn.setId(id);
			sqlMapClient.insert("face.insert_comparePhotoNumber", cpn);
			return cpn;
		}
	}
	
	private long getLatestTotalNumber() throws Exception{
		List<ComparePhotoNumber> list = sqlMapClient.queryForList("face.getLatestTotalNumber");
		if(list != null && list.size() > 0){
			return list.get(0).getTotalNumber();
		}else{
			return 0;
		}
	}
	
	public static void main(String[] args) throws Exception{
		TotalNumberService tns = TotalNumberService.getInstance();
		tns.addRequestNumber();
		tns.addRequestNumber();
	}

}
